<template>
    <div class="add_rank_container">
        <div class="form_card">
            <el-form ref="formRef" :model="form" label-width="120px">
                <el-form-item label="会员等级">
                    <div>{{ state.memberLevel }}</div>
                </el-form-item>
                <el-form-item label="会员名称" prop="memberLevelName" :rules="rules.required">
                    <el-input
                        class="input_widtn_400"
                        v-model="form.memberLevelName"
                        placeholder="请输入会员名称，不超过10个"
                        maxlength="10" />
                </el-form-item>
                <el-form-item
                    label="升级条件"
                    class="el-form-item_mb_15"
                    prop="memberUplevelCondition"
                    :rules="rules.memberUplevelCondition">
                    <div class="content_card">
                        <div v-if="state.memberLevel === 'VIP1'" class="input_box input_p0">无门槛</div>
                        <div v-else class="input_box input_p0">
                            <el-input-number
                                class="input_widtn_120"
                                v-model="form.memberUplevelCondition"
                                :min="0"
                                :controls="false"
                                placeholder="请输入" />
                            <div class="input_text">成长值</div>
                        </div>
                        <div v-if="state.memberLevel === 'VIP1'" class="desc">
                            VIP1升级条件无门槛，即0成长值，不支持设置成长值门槛
                        </div>
                        <div v-else class="desc">需高于上一等级成长值：{{ state.lastLevel }}</div>
                    </div>
                </el-form-item>
                <div class="huiyuanquanyi">
                    <div class="label">会员权益</div>
                    <div>
                        <div class="quanyi" v-for="(item, index) in form.memberPriority" :key="`k${index}`">
                            <el-checkbox v-model="item.checked" class="duobei_checkbox" size="large">
                                {{ item.priorityInnerName }}
                            </el-checkbox>
                            <el-form-item
                                v-if="item.checked && item.priorityType == 2"
                                label-width="0"
                                :prop="`memberPriority.${index}.priorityVal`"
                                :rules="rules.required"
                                class="input_box checkbox_input_mt">
                                <el-input-number
                                    v-model="item.priorityVal"
                                    :min="1"
                                    :max="99"
                                    :precision="1"
                                    :controls="false"
                                    placeholder="支持小数点后1位" />
                                <div class="input_text">倍</div>
                            </el-form-item>
                        </div>
                    </div>
                </div>
                <div class="huiyuanquanyi">
                    <div class="label">升级礼包</div>
                    <div>
                        <div class="quanyi">
                            <el-checkbox
                                v-model="form.memberUplevelGift.bonusPoints"
                                :true-label="2"
                                :false-label="1"
                                @change="onChangeBonusPoints"
                                class="duobei_checkbox"
                                size="large">
                                送积分
                            </el-checkbox>
                            <el-form-item
                                v-if="form.memberUplevelGift.bonusPoints == 2"
                                label-width="0"
                                prop="memberUplevelGift.bonusPointsPoint"
                                :rules="rules.required"
                                class="input_box checkbox_input_mt">
                                <el-input-number
                                    v-model="form.memberUplevelGift.bonusPointsPoint"
                                    :min="1"
                                    :max="99999"
                                    :precision="0"
                                    :controls="false"
                                    placeholder="请输入" />
                                <div class="input_text">分</div>
                            </el-form-item>
                        </div>
                    </div>
                </div>
            </el-form>
        </div>
        <div class="btn_card">
            <el-button @click="routerBack">取消</el-button>
            <el-button type="primary" @click="onSubmit(formRef)">保存</el-button>
        </div>
    </div>
</template>

<script setup>
import { floatMultiply, floatDivide } from '@/commons/utils';
import { cloneDeep } from '@/commons/utils';
import storage from '@/commons/storage';
import request from '@/request';
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue';
import { setLayout, resetLayout } from '@/hooks/layout';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';

const router = useRouter();
const route = useRoute();
const formRef = ref(null);
const state = reactive({
    memberLevel: '',
    nextLevel: 0,
    lastLevel: 0
});
const form = reactive({
    memberLevelName: '',
    memberUplevelCondition: null,
    memberPriority: [],
    memberUplevelGift: {
        bonusPoints: 1,
        bonusPointsPoint: null
    }
});
const validateMemberUplevelCondition = (rule, value, callback) => {
    if (state.memberLevel === 'VIP1') {
        callback();
    } else {
        if (value <= state.lastLevel) {
            callback(new Error('需高于上一等级成长值'));
        } else {
            callback();
        }
    }
};
const rules = reactive({
    required: [{ required: true, message: '此字段必填', trigger: 'blur' }],
    memberUplevelCondition: [
        { required: true, message: '此字段必填', trigger: 'blur' },
        { validator: validateMemberUplevelCondition, trigger: 'blur' }
    ]
});
const onChangeBonusPoints = v => {
    if (v === 1) {
        form.memberUplevelGift.bonusPointsPoint = null;
    }
};
const routerBack = () => {
    router.back();
};

const onSubmit = async formEl => {
    if (!formEl) return;
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let params = cloneDeep(form);
            params.memberPriority = params.memberPriority
                .filter(item => item.checked)
                .map(item => {
                    delete item.checked;
                    delete item.priorityInnerName;
                    item.priorityVal = item.priorityVal || 0;
                    return item;
                });
            if (params.memberUplevelGift.bonusPoints == 2) {
                params.memberUplevelGift.bonusPointsPoint = floatMultiply(
                    params.memberUplevelGift.bonusPointsPoint,
                    100
                );
            }
            if (form.id) {
                await request('editRankServ', params);
                ElMessage.success('编辑成功');
                routerBack();
            } else {
                await request('addRankServ', params);
                ElMessage.success('添加成功');
                routerBack();
            }
        }
    });
};
const getDetail = async () => {
    const { data } = await request('getDetailRankServ', { id: route.query.id });
    state.memberLevel = data.memberLevel;
    state.lastLevel = data.lastLevel;
    state.nextLevel = data.nextLevel;
    form.id = data.id;
    form.memberLevelName = data.memberLevelName;
    form.memberUplevelGift = data.memberUplevelGift;
    form.memberUplevelGift.bonusPoints = data.memberUplevelGift.bonusPoints;
    if (form.memberUplevelGift.bonusPoints == 2) {
        form.memberUplevelGift.bonusPointsPoint = floatDivide(data.memberUplevelGift.bonusPointsPoint, 100);
    }
    form.memberLevelName = data.memberLevelName;
    form.memberUplevelCondition = data.memberUplevelCondition;
    form.memberPriority.forEach(item => {
        let findItem = data.memberPriority.find(i => i.priorityId == item.priorityId);
        if (findItem) {
            item.checked = true;
            item.priorityVal = findItem.priorityVal;
        }
    });
};
const initData = async () => {
    const { data } = await request('getRightsListServ', { corpId: storage.get('ZW-TENANT-ID') });

    let newArr = [];
    data.forEach(item => {
        newArr.push({
            priorityId: item.id,
            priorityType: item.priorityType,
            priorityInnerName: item.priorityInnerName,
            checked: false,
            priorityVal: null
        });
    });
    form.memberPriority = newArr;
    route.query.id && getDetail();
};
onMounted(() => {
    initData();
    state.memberLevel = route.query.memberLevel;
    state.lastLevel = +route.query.v || 0;
    setLayout();
});
onUnmounted(() => {
    resetLayout();
});
</script>

<style lang="scss" src="./index.scss" scoped></style>
